<template>
  <div class="box">
    <div class="hysx">
      <div class="line">行业授信</div>
      <div class="item">
        <div class="itemLine">
          <span class="itemIcon"></span>
          <div class="itemText">行内授信总览</div>
        </div>
        <div class="hnsxzl">
          <div class="table1">
            <el-table :data="tableData" style="width: 100%">
              <el-table-column
                prop="creditSubLimitName"
                label="分项名称"
                resizable=true
                align="center"
                fit=true
              ></el-table-column>
              <el-table-column
                prop="creditSubLimit"
                label="授信总额（万）"
                align="center"
                fit=true
                :formatter='amountFormatter'
              ></el-table-column>
              <el-table-column
                prop="creditSubLimitOccupied"
                label="占用额度（万）"
                align="center"
                fit=true
                :formatter='amountFormatter'
              ></el-table-column>
              <el-table-column
                prop="creditSubLimitAvailable"
                label="剩余额度（万）"
                align="center"
                fit=true
                :formatter='amountFormatter'
              ></el-table-column>
              <el-table-column
                prop="proportion"
                label="占用/总额比(%)"
                align="center"
                fit=true
                :formatter='proportionFormatter'
              ></el-table-column>
              <el-table-column
                prop="subLimitMaturityDate"
                label="授信到期日"
                width="120px"
                align="center"
                fit=true
                :formatter='dateFormatter'
              ></el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div class="item">
        <div class="itemLine">
          <span class="itemIcon"></span>
          <div class="itemText">分项授信统计</div>
        </div>

        <div class="tubiao1">
          <div class="tubiao1Item">
            <div class="fxsxtj1">
              <el-radio-group
                v-model="fxsxtj1"
                size="mini"
                @change="statisticsRadio1Fn"
              >
                <el-radio-button label="总额与剩余">总额与剩余</el-radio-button>
                <el-radio-button label="已占用">已占用</el-radio-button>
              </el-radio-group>
            </div>
            <div class="fxsxtjSelect">
              <span>分项名称</span>
              <el-select
                v-model="creditOccupySubLimitId"
                placeholder="请选择"
                @change="selectFn"
              >
                <el-option
                  v-for="item in options1"
                  :key="item.creditSubLimitId"
                  :label="item.creditSubLimitName"
                  :value="item.creditSubLimitId"
                >
                </el-option>
              </el-select>
            </div>
          </div>
          <div id="ceshi" v-show="this.ceshi1Display1 === true"></div>
          <div id="ceshi2" v-show="this.ceshi1Display2  === true"></div>
          <!-- <div id="ceshi"></div>
          <div id="ceshi2"></div> -->
        </div>
      </div>
      <div class="item">
        <div class="itemLine">
          <span class="itemIcon"></span>
          <div class="itemText">分项授信分布与明细</div>
        </div>
        <div class="tubiao2">
          <div class="tubiao2box"></div>
          <div></div>
          <div class="main">
            <div class="pie1Box">
              <div class="fxsxfbSelect">
                <span class="selectLabel">分项名称</span>
                <el-select
                  v-model="creditOccupySubLimitId2"
                  placeholder="请选择"
                  @change="select1Fn"
                >
                  <el-option
                    v-for="item in options1"
                    :key="item.creditSubLimitId"
                    :label="item.creditSubLimitName"
                    :value="item.creditSubLimitId"
                  >
                  </el-option>
                </el-select>
              </div>
              <div id="pie1"></div>
            </div>
            <div class="table">
              <div class="fxsxtj2">
                <div>
                  <el-radio-group
                    v-model="fxsxtj2"
                    size="mini"
                    @change="statisticsRadio2Fn"
                  >
                    <el-radio-button label="今年以来">今年以来</el-radio-button>
                    <el-radio-button label="近一年">近一年</el-radio-button>
                    <el-radio-button label="全部">全部</el-radio-button>
                  </el-radio-group>
                  <el-date-picker
                    v-model="fxsxfbTime"
                    class="fxsxfbTime"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始"
                    end-placeholder="结束"
                    size="mini"
                  >
                  </el-date-picker>
                </div>
              </div>
              <el-table :data="tableData2">
                <el-table-column
                  prop="tradeId"
                  label="交易编号"
                  width="80px"
                  align="center"
                ></el-table-column>
                <el-table-column
                  prop="occupyDate"
                  label="授信占用日期"
                  align="center"
                  :formatter="dateFormatter"
                ></el-table-column>
                <el-table-column
                  prop="portfolioId"
                  label="投资组合名称"
                  align="center"
                ></el-table-column>
                <el-table-column
                  prop="actualOccupiedLimit"
                  label="占用额度（万）"
                  align="center"
                  :formatter="amountFormatter"
                ></el-table-column>
                <el-table-column
                  prop="availableAmount"
                  label="剩余总额（万）"
                  align="center"
                  :formatter="amountFormatter"
                ></el-table-column>
                <el-table-column
                  prop="proportion"
                  label="累计占用比例（%）"
                  align="center"
                  :formatter="proportionFormatter"
                ></el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getCreditInfo,
  getCreditInfoDetails,
  getCreditSubType,
  getCreditInfoDetailsStatics,
} from '@/api/customerList/index.js';
import moment from 'moment';
export default {
  props: {
    type: {
      type: String | Number,
    },
    customerId: {
      type: String,
    },
  },
  data() {
    return {
      // customerId:'test01',
      tableData: [],
      fxsxtj2: '今年以来',
      fxsxtj1: '总额与剩余',
      ceshi1Display1:true,
      ceshi1Display2:true,
      options: [],
      creditOccupySubLimitId: '',
      creditOccupySubLimitId2: '',
      fxsxfbTime: '',
      options1: [],
      tbList: [],
      value2: [],
      tableData2: [],
      startDate: '',
      endDate: '',
      tbTitle: [],
      creditInfoDetailsStaticsDateList: [],
      totalAmountList: [],
      availableAmountList: [],
      occupiedAmountList: [],
      defaultValue:'',
      piStartDate:'',
      piEndDate:''
    };
  },
  watch: {
    fxsxfbTime(newVal, oldVal) {  
      this.startDate = new Date(newVal[0]).format('yyyyMMdd');
      this.endDate = new Date(newVal[1]).format('yyyyMMdd');
      console.log(this.startDate, this.endDate);
      this.select1Fn(this.creditOccupySubLimitId);
      // 这里可以执行更多的逻辑
    }
  },
  async created() {
    console.log('created')
    const res = await getCreditInfo({ customerId: this.customerId });
    debugger;
    console.log(res)
    this.tableData = res.data.records.map((v) => {
      return {
        ...v,
        proportion:this.calProportionFormatter(v.creditSubLimit,v.creditSubLimitOccupied)

      };
    });
    // const creditSubTypes = await getCreditInfoDetails({
    //   customerId: '',
    //   creditOccupySubLimitId: '',
    //   startDate: '',
    //   endDate: '',
    // });
    const creditSubTypes = await getCreditSubType({customerId:this.customerId});
    this.options1 = creditSubTypes.data.records;
    if (creditSubTypes.data.records.length > 0) {
      // this.creditOccupySubLimitId = creditSubTypes.data.records[0].creditSubLimitId;
      creditSubTypes.data.records[0].creditSubLimitId;
      console.log(creditSubTypes.data.records[0].creditSubLimitId);
      this.creditOccupySubLimitId = this.options1[0].creditSubLimitId;
      this.creditOccupySubLimitId2 = this.options1[0].creditSubLimitId;
      const params = {
        customerId: this.customerId,
        creditOccupySubLimitId2:this.creditOccupySubLimitId ,
        startDate: '',
        endDate: '',
      };
      const initCreditInfoDetails = await getCreditInfoDetails(params);
      this.tbTitle = [];
      console.log(initCreditInfoDetails,'initCreditInfoDetails');

      let totalOccupiedAmount = initCreditInfoDetails.data.records.reduce((sum, item) => sum + item.occupiedAmount, 0);
      let totalAmount = initCreditInfoDetails.data.records[0].totalAmount;
      let totalAvailableAmount = totalAmount - totalOccupiedAmount;
      console.log('aaaaaaaaa',totalAmount,totalOccupiedAmount,this.proportionFormatter(null,null,this.calProportionFormatter(totalAmount,totalOccupiedAmount)));
      console.log('bbbbbbbbb',totalAmount,totalAvailableAmount,this.proportionFormatter(null,null,this.calProportionFormatter(totalAmount,totalAvailableAmount)));
      this.tblist = [
        {value:totalOccupiedAmount,
          name: "占用额度\n" + this.proportionFormatter(null,null,this.calProportionFormatter(totalAmount,totalOccupiedAmount)) + "，" + this.amountFormatter(null,null,totalOccupiedAmount)+ '万'
        },{value:totalAvailableAmount,
          name: "剩余总额\n" + this.proportionFormatter(null,null,this.calProportionFormatter(totalAmount,totalAvailableAmount)) + "，" + this.amountFormatter(null,null,totalAvailableAmount)+ '万'
        }];
      // this.tblist = initCreditInfoDetails.data.records.it((v) => {
      //   this.tbTitle.push(v.occupyDate);
      //   return {
      //     proportion: v.proportion,
      //     name: v.actualOccupiedLimit + '',
      //     value: v.availableAmount,
      //   };
      // });
      this.tableData2 = initCreditInfoDetails.data.records;
      const params2 = {
        customerId: this.customerId,
        creditOccupySubLimitId: this.creditOccupySubLimitId,
      };
      const selectedCreditInfoDetails = await getCreditInfoDetailsStatics(params2);
      this.totalAmountList = [];
      this.availableAmountList = [];
      this.occupiedAmountList = [];
      selectedCreditInfoDetails.data.records.forEach((v) => {
        this.creditInfoDetailsStaticsDateList.push(v.occupyDate);
        this.totalAmountList.push(v.totalAmount);
        this.availableAmountList.push(v.availableAmount);
        this.occupiedAmountList.push(v.occupiedAmount);
      });
      this.selectFn(this.creditOccupySubLimitId);
      this.select1Fn(this.creditOccupySubLimitId);
      this.pie1Init();
      this.drawLine();

      console.log(res4, 6666);
    }
  },
  async mounted() {
    this.drawLine2();
    this.statisticsRadio2Fn();
    this.ceshi1Display2 = false;
    // await this.selectFn();
    // await this.select1Fn();
    //   this.drawLine();
  },
  methods: {
    handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    async statisticsRadio2Fn(value = '今年以来') {
      const today = moment();
      switch (value) {
        case '今年以来':
          // 获取一年前的日期
          const YearAgo = today.startOf('years').format('YYYYMMDD');
          this.startDate = YearAgo;
          break;
        case '近一年':
          // 获取一年前的日期
          const oneYearAgo = today.subtract(1, 'years').format('YYYYMMDD');
          this.startDate = oneYearAgo;
          break;
        case '近三年':
          // 获取一年前的日期
          const threeYearAgo = today.subtract(3, 'years').format('YYYYMMDD');
          this.startDate = threeYearAgo;
          break;
        case '全部':
          this.startDate = '';
          this.endDate = '';
          break;
        default:
          break;
      }
      const params = {
        customerId: this.customerId,
        creditOccupySubLimitId: '',
        startDate: this.startDate,
        endDate: this.endDate,
      };
      const initCreditInfoDetails = await getCreditInfoDetails(params);
      this.tableData2 = initCreditInfoDetails.data.records;
    },

    async selectFn(val) {
      console.log("selectFn",val);
      const params = {
        customerId: this.customerId,
        creditOccupySubLimitId: val,
      };
      const selectedCreditInfoDetails = await getCreditInfoDetailsStatics(params);
      this.creditInfoDetailsStaticsDateList = [];
      this.totalAmountList = [];
      this.availableAmountList = [];
      this.occupiedAmountList = [];
      selectedCreditInfoDetails.data.records.forEach((v) => {
        this.creditInfoDetailsStaticsDateList.push(this.dateFormatter(null,null,v.occupyDate));
        this.totalAmountList.push(this.amountFormatter(null,null,v.totalAmount));
        this.availableAmountList.push(this.amountFormatter(null,null,v.availableAmount) );
        this.occupiedAmountList.push(this.amountFormatter(null,null,v.occupiedAmount) );
      });
      this.$nextTick(() => {
        this.drawLine();
        this.drawLine2();
      });
    },
    async select1Fn(val) {
      console.log("select1Fn");
      const params = {
        customerId: this.customerId,
        creditOccupySubLimitId: val,
        startDate: this.startDate,
        endDate: this.endDate,
      };
      const initCreditInfoDetails = await getCreditInfoDetails(params);

      this.tableData2 = initCreditInfoDetails.data.records;
      this.tblist = [];
      if (this.tableData2.length > 0) {
        let totalOccupiedAmount = initCreditInfoDetails.data.records.reduce((sum, item) => sum + item.occupiedAmount, 0);
        let totalAmount = initCreditInfoDetails.data.records[0].totalAmount;
        let totalAvailableAmount = totalAmount - totalOccupiedAmount;
        console.log(totalAmount,totalOccupiedAmount,this.proportionFormatter(null,null,this.calProportionFormatter(totalAmount,totalOccupiedAmount)));
        console.log(totalAmount,totalAvailableAmount,this.proportionFormatter(this.calProportionFormatter(totalAmount,totalAvailableAmount)));
        this.tblist = [
        {value:totalOccupiedAmount,
          name: "占用额度\n" + this.proportionFormatter(null,null,this.calProportionFormatter(totalAmount,totalOccupiedAmount)) + "，" + this.amountFormatter(null,null,totalOccupiedAmount) + '万'
        },{value:totalAvailableAmount,
          name: "剩余总额\n" + this.proportionFormatter(null,null,this.calProportionFormatter(totalAmount,totalAvailableAmount)) + "，" + this.amountFormatter(null,null,totalAvailableAmount) + '万'
        }];
      }

    },
    async statisticsRadio1Fn(value = '总额与剩余') {
      console.log(value,"statisticsRadio1Fn")
      switch (value) {
        case '总额与剩余':
          // 获取一年前的日期
          this.fxsxtj1 = value;
          this.ceshi1Display1 = true;
          this.ceshi1Display2 = false;
          this.drawLine();
          break;
        case '已占用':
          // 获取一年前的日期
          this.fxsxtj1 = value;
          this.ceshi1Display1 = false;
          this.ceshi1Display2 = true;
          this.drawLine2();
          break;
        default:
          break;
      }
    },
    drawLine() {
      console.log(' this.totalAmountList', this.totalAmountList);
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById('ceshi'));
      // 绘制图表
      var option = {
        tooltip: {
          trigger: 'axis',
        },
        areaStyle: {
          color: 'rgb(8,176,240)',
        },
        legend: {
          data: ['授信总额（万）','剩余总额（万）'],
          selected: {
            // 选中'系列1'
            '授信总额（万）': true,
            // 不选中'系列2'
            '剩余总额（万）': true
          },
          textStyle: {
            color: "white", // 图例文字颜色
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.creditInfoDetailsStaticsDateList,
          axisLine: {
            lineStyle: {
              color: '#fff',
            },
          },
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#fff',
            },
          },
        },
        series: [
          {
            data: this.availableAmountList,
            name: '剩余总额（万）',
            type: 'line',
            areaStyle: { color: 'rgb(8,176,240)' },
            lineStyle: {
              color: 'rgb(8,176,240)',
            },
          },
          {
            name: '授信总额（万）',
            type: 'line',
            data: this.totalAmountList,
            lineStyle: {
              color: '#fff',
            },
          },
        ],
      };

      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    },
    drawLine2() {
      // 基于准备好的dom，初始化echarts实例
      console.log(this.creditInfoDetailsStaticsDateList,this.occupiedAmountList,"drawLine2");
      let myChart1 = this.$echarts.init(document.getElementById('ceshi2'));
      // 绘制图表
      var option = {
        tooltip: {
          trigger: 'axis',
        },
        areaStyle: {
          color: 'rgb(8,176,240)',
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.creditInfoDetailsStaticsDateList,
          axisLine: {
            lineStyle: {
              color: '#fff',
            },
          },
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#fff',
            },
          },
        },
        series: [
          {
            name: '已占用',
            type: 'line',
            data: this.occupiedAmountList,
            lineStyle: {
              color: '#fff',
            },
          },
          
        ],
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart1.setOption(option);
      // echarts.init()
    },
    // drawLine2() {
    //   // 基于准备好的dom，初始化echarts实例
    //   let myChart = this.$echarts.init(document.getElementById('tubiao2'));
    //   // 绘制图表
    //   let option = {
    //     tooltip: {
    //       trigger: 'item',
    //     },

    //     series: [
    //       {
    //         name: 'Access From',
    //         type: 'pie',
    //         radius: '50%',
    //         data: [
    //           { value: 1048, name: 'Search Engine' },
    //           { value: 735, name: 'Direct' },
    //           { value: 580, name: 'Email' },
    //           { value: 484, name: 'Union Ads' },
    //           { value: 300, name: 'Video Ads' },
    //         ],
    //         emphasis: {
    //           itemStyle: {
    //             shadowBlur: 10,
    //             shadowOffsetX: 0,
    //             shadowColor: 'rgba(0, 0, 0, 0.5)',
    //           },
    //         },
    //       },
    //     ],
    //   };

    //   // 使用刚指定的配置项和数据显示图表。
    //   myChart.setOption(option);
    // },
    pie1Init() {
      let myChart = this.$echarts.init(document.getElementById('pie1'));
      let option;
      console.log(this.tblist,666);
      option = {
        tooltip: {
          trigger: 'item',
        },
        top:20,
        series: [
          {
            name: '',
            type: 'pie',
            radius: '70%',
            data: this.tblist,
            itemStyle: {
              // 为每一块设置颜色
              normal: {
                color: function (params) {
                  // 自定义颜色
                  var colorList = [
                    '#fff',
                    '#08b0f0',
                    '#ffff03',
                    '#f4b183',
                    '#a9d18e',
                  ];
                  return colorList[params.dataIndex];
                },
              },
            },
          },
        ],
      };
      myChart.setOption(option);
    },
    dateFormatter(row, column, cellValue, index) {
      var result = cellValue.substring(0,4) + '-' + cellValue.substring(4,6) + '-' + cellValue.substring(6,8)  
      return result;
    },
    amountFormatter(row, column, cellValue, index) {
      if (!isNaN(Number(cellValue))) {
        return Math.round(cellValue/10000);
      } else {
        return '-';
      }
    },
    proportionFormatter(row, column, cellValue, index) {
      if (cellValue !== '-') {
        return (cellValue*100).toString().substring(0,4) + '%';
      }
      return cellValue;
    },
    calProportionFormatter(v1,v2) {
      var n1 = new Number(v1);
      var  n2 = new Number(v2); 
      if (!isNaN(n1) && !isNaN(n2) && n1 !== 0) {
        if (!isNaN(n2/n1))
          return n2/n1;
      } 
        return '-';
    }
  },
};
</script>

<style lang="scss" scoped>
.box {
  height: calc(100vh - 160px);
  overflow: scroll;
  .hysx {
    .line {
      height: 45px;
      line-height: 45px;
      background-color: rgb(52, 64, 96);
      padding-left: 19px;
      box-sizing: border-box;
      font-weight: bold;
      font-size: 14px;
    }
  }
}
.itemIcon {
  width: 5px;
  height: 28px;
  background-color: #08b0f0;
  display: inline-block;
  position: absolute;
  top: 50%;
  left: 12px;
  transform: translateY(-50%);
}
.itemText {
  display: inline-block;
  padding-left: 25px;
}
.itemLine {
  height: 38px;
  line-height: 38px;
  position: relative;
  margin-top: 5px;
}
#ceshi {
  height: 500px;
}
#ceshi2 {
  height: 500px;
  width: 100%;
}
::v-deep {
  .el-table {
    min-height: 440px;
  }
  .el-table th.el-table__cell {
    background-color: #1c2238;
    color: #fff;
  }
}
.table1 {
  border: 1px solid rgb(57, 81, 127);
  padding: 11px 12px;
}
.table {
  flex: 1;
}
.fxsxtj1 {
}
.hnsxzl {
  //   border: 1px solid rgb(57, 81, 127);
  padding: 10px 12px;
}
.tubiao1 {
  border: 1px solid rgb(57, 81, 127);
  margin: 10px 12px;
  padding-right: 20px;
}
.tubiao1Item {
  padding-top: 20px;
  padding-left: 20px;
}
.tubiao2 {
  border: 1px solid rgb(57, 81, 127);
  margin: 10px 12px;
  padding-top: 20px;
  padding-right: 20px;
  .tubiao2box {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
}
.fxsxtj2 {
  margin-left: 10px;
  margin-top: 10px;
  margin-bottom: 20px;
  text-align: right;
}
.fxsxtjSelect {
  margin-top: 20px;
  span {
    margin-right: 5px;
  }
}
.fxsxfbSelect {
  padding-left: 50px;
  .selectLabel {
    margin-right: 5px;
  }
}
.fxsxfbTime {
  width: 250px;
  margin-left: 5px;
  vertical-align: top;
  ::v-deep {
    .el-range-input {
      width: 100px;
    }
  }
}
.main {
  display: flex;
  justify-content: space-between;
  #tubiao2 {
    width: 300px;
    height: 300px;
  }
}
::v-deep {
  .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    background-color: #8c97bb;
  }
  .el-radio-button__inner {
    background-color: #1b2238;
    border-color: #6794df;
    color: #fff;
  }
  .el-date-editor--monthrange.el-input,
  .el-date-editor--monthrange.el-input__inner {
    width: 200px;
    line-height: 28px;
  }
  .el-input__inner,
  .el-date-editor .el-range-input {
    background-color: #1b2238;
    border-color: #6794df;
  }
  .el-range-editor.el-input__inner {
    height: 28px;
  }
  .el-date-editor .el-range__icon,
  .el-date-editor .el-range__close-icon {
    line-height: 0;
  }
  .el-radio-button:first-child .el-radio-button__inner {
    border-color: #6794df;
  }
}
#pie1 {
  width: 90%;
  height: 300px;
  margin-top:30px;
}
.pie1Box {
  flex: 1;
}
</style>
